package cn.edu.kzjsxy.graduationproject.service.impl;

import cn.edu.kzjsxy.graduationproject.common.Page;
import cn.edu.kzjsxy.graduationproject.common.Result;
import cn.edu.kzjsxy.graduationproject.dto.LoginRequest;
import cn.edu.kzjsxy.graduationproject.entity.Users;
import cn.edu.kzjsxy.graduationproject.mapper.UsersMapper;
import cn.edu.kzjsxy.graduationproject.service.IUsersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 用户表：用于存储系统用户信息 服务实现类
 * </p>
 *
 * @author chén jiā jùn
 * @since 2024-04-14
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

	@Autowired
	UsersMapper usersMapper;

	// redis的service
	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Value("${spring.redis.cache.redis.time-to-live}")
	private int cacheTimeToLive;

	@Override
	public List<Users> selectUserByCondition( Users user) {
		// 执行查询
		List<Users> userList = usersMapper.selectUserByCondition(user);
		return userList;
	}

	@Override
	public Result<PageInfo<Users>> selectUserByPage(Page page, Users user) {
		// 设置分页
		PageHelper.startPage(page.getPageNum(), page.getPageSize());
		// 执行查询
		List<Users> userList = usersMapper.selectUserByCondition(user);
		PageInfo<Users> pageInfo = new PageInfo<>(userList);
		return Result.success(pageInfo);
	}


//	用户登录
	@Override
	public Result<Users> login(LoginRequest loginRequest) {
		Users user = usersMapper.login(loginRequest);
		if(user==null){
			return Result.error("账号不存在或密码错误!");
		}
		if(user.getIsLocked()){
			return Result.error("账号被锁定，无法登录请联系管理员!");
		}
		user.setToken(generateToken(loginRequest.getUserId()));
		return  Result.success(user);
	}


	public String generateToken(String userId) {
		// 生成 UUID 作为 Token
		String token = UUID.randomUUID().toString();
		// 将 Token 和 UserID 存储到 Redis 中，并设置过期时间
		redisTemplate.opsForValue().set(token, userId, cacheTimeToLive, TimeUnit.SECONDS);
		return token;
	}

}
